from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import Optional

from database import get_db
from models import Question, User
from schemas import (
    QuestionCreate,
    QuestionUpdate,
    QuestionResponse,
    QuestionListResponse
)
from utils.auth_utils import get_current_user
from logger import logging

router = APIRouter(
    prefix="/api/questions",
    tags=["问题管理"],
)


@router.get("/", response_model=QuestionListResponse)
def get_questions(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回的记录数"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    status: Optional[str] = Query(
        None, description="状态筛选：active-启用, inactive-停用"),
    category: Optional[str] = Query(None, description="分类筛选"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取问题列表（需要认证）

    支持以下筛选条件：
    - keyword: 搜索问题标题或分类
    - status: 按状态筛选
    - category: 按分类筛选
    """
    try:
        # 构建查询
        query = db.query(Question)

        # 关键词搜索
        if keyword:
            search_term = f"%{keyword}%"
            query = query.filter(
                or_(
                    Question.title.ilike(search_term),
                    Question.category.ilike(search_term)
                )
            )

        # 状态筛选
        if status and status in ["active", "inactive"]:
            query = query.filter(Question.status == status)

        # 分类筛选
        if category:
            query = query.filter(Question.category.ilike(f"%{category}%"))

        # 获取总数
        total = query.count()

        # 分页并按ID倒序排列
        questions = query.order_by(Question.id.desc()).offset(
            skip).limit(limit).all()

        logging.info(f"用户 {current_user.username} 获取问题列表，共 {total} 条记录")

        return QuestionListResponse(
            total=total,
            questions=[QuestionResponse.model_validate(q) for q in questions]
        )
    except Exception as e:
        logging.error(f"获取问题列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取问题列表失败: {str(e)}")


@router.get("/{question_id}", response_model=QuestionResponse)
def get_question(
    question_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取问题详情（需要认证）"""
    try:
        question = db.query(Question).filter(
            Question.id == question_id).first()

        if not question:
            raise HTTPException(
                status_code=404, detail=f"问题 ID {question_id} 不存在")

        logging.info(f"用户 {current_user.username} 获取问题详情 ID: {question_id}")

        return QuestionResponse.model_validate(question)
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"获取问题详情失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取问题详情失败: {str(e)}")


@router.post("/", response_model=QuestionResponse)
def create_question(
    question_data: QuestionCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建新问题（需要认证）"""
    try:
        # 检查标题是否重复
        existing_question = db.query(Question).filter(
            Question.title == question_data.title.strip()
        ).first()

        if existing_question:
            raise HTTPException(status_code=400, detail="问题标题已存在")

        # 创建新问题
        new_question = Question(
            title=question_data.title.strip(),
            category=question_data.category.strip(),
            status="active"
        )

        db.add(new_question)
        db.commit()
        db.refresh(new_question)

        logging.info(
            f"用户 {current_user.username} 创建新问题 ID: {new_question.id}, 标题: {new_question.title}")

        return QuestionResponse.model_validate(new_question)
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logging.error(f"创建问题失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"创建问题失败: {str(e)}")


@router.put("/{question_id}", response_model=QuestionResponse)
def update_question(
    question_id: int,
    question_data: QuestionUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新问题信息（需要认证）"""
    try:
        # 查找问题
        question = db.query(Question).filter(
            Question.id == question_id).first()

        if not question:
            raise HTTPException(
                status_code=404, detail=f"问题 ID {question_id} 不存在")

        # 更新标题
        if question_data.title is not None:
            title = question_data.title.strip()
            # 检查标题是否与其他问题重复
            existing_question = db.query(Question).filter(
                Question.title == title,
                Question.id != question_id
            ).first()

            if existing_question:
                raise HTTPException(status_code=400, detail="问题标题已存在")

            question.title = title

        # 更新分类
        if question_data.category is not None:
            question.category = question_data.category.strip()

        # 更新状态
        if question_data.status is not None:
            if question_data.status not in ["active", "inactive"]:
                raise HTTPException(
                    status_code=400, detail="状态值必须为 active 或 inactive")
            question.status = question_data.status

        db.commit()
        db.refresh(question)

        logging.info(f"用户 {current_user.username} 更新问题 ID: {question_id}")

        return QuestionResponse.model_validate(question)
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logging.error(f"更新问题失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"更新问题失败: {str(e)}")


@router.delete("/{question_id}")
def delete_question(
    question_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除问题（需要认证）"""
    try:
        # 查找问题
        question = db.query(Question).filter(
            Question.id == question_id).first()

        if not question:
            raise HTTPException(
                status_code=404, detail=f"问题 ID {question_id} 不存在")

        question_title = question.title
        question_category = question.category

        # 删除问题
        db.delete(question)
        db.commit()

        logging.info(
            f"用户 {current_user.username} 删除问题 ID: {question_id}, 标题: {question_title}")

        return {
            "message": "问题删除成功",
            "id": question_id,
            "title": question_title,
            "category": question_category
        }
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logging.error(f"删除问题失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"删除问题失败: {str(e)}")


@router.patch("/{question_id}/toggle-status", response_model=QuestionResponse)
def toggle_question_status(
    question_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """切换问题状态（启用/停用）（需要认证）"""
    try:
        # 查找问题
        question = db.query(Question).filter(
            Question.id == question_id).first()

        if not question:
            raise HTTPException(
                status_code=404, detail=f"问题 ID {question_id} 不存在")

        # 切换状态
        question.status = "inactive" if question.status == "active" else "active"

        db.commit()
        db.refresh(question)

        logging.info(
            f"用户 {current_user.username} 切换问题 ID: {question_id} 状态为: {question.status}")

        return QuestionResponse.model_validate(question)
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logging.error(f"切换问题状态失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"切换问题状态失败: {str(e)}")


@router.patch("/{question_id}/increment-usage", response_model=QuestionResponse)
def increment_question_usage(
    question_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """增加问题使用次数（需要认证）"""
    try:
        # 查找问题
        question = db.query(Question).filter(
            Question.id == question_id).first()

        if not question:
            raise HTTPException(
                status_code=404, detail=f"问题 ID {question_id} 不存在")

        # 增加使用次数
        question.usage_count += 1

        db.commit()
        db.refresh(question)

        logging.info(
            f"用户 {current_user.username} 增加问题 ID: {question_id} 使用次数，当前: {question.usage_count}")

        return QuestionResponse.model_validate(question)
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logging.error(f"增加问题使用次数失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"增加问题使用次数失败: {str(e)}")
